package com.ray.controller.base;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.ray.log.WebLog;
import com.ray.model.Msg;
import com.ray.model.MsgReply;
import com.ray.model.MsgUser;
import com.ray.model.User;
import com.ray.util.JsonKit;
import com.ray.util.Ret;
import com.ray.websocket.SysmsgWebsocket;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/msg")
public class MsgController extends BaseController {

    @RequestMapping("getMsgList")
    @WebLog(description = "请求获取消息列表")
    public Ret getMsgList(@RequestBody Map params) {
        String sqlString = "SELECT t1.id,t2.no,t2.title,t2.content,t2.create_time,t1.is_read"
                + " FROM msg_user t1 LEFT JOIN msg t2 ON t1.msg_no = t2.no"
                + " where t1.userid = '" + getSessionUserId() + "'"
                + " and t1.region = '" + getSessionUserRegion() + "'";
        sqlString += " and t1.is_read = " + params.get("is_read");
        sqlString += " order by create_time desc";
        SqlPara sql = new SqlPara().setSql(sqlString);
        Page<Record> page = Db.use(base).paginate(1, Integer.valueOf(params.get("size").toString()), sql);
        return Ret.ok("msg", "成功").set("list", JsonKit.toJson(page.getList())).set("totalResult", page.getTotalRow());
    }

    @RequestMapping("getMsgByNo")
    @WebLog(description = "请求获取消息详情")
    public Ret getMsgByNo(@RequestBody Map params) {
        Msg msg = Msg.dao.findFirst("select * from msg where no = ?", params.get("no"));
        msg.setHits(msg.getHits() + 1);
        msg.update();
        MsgUser mu = MsgUser.dao.findFirst("select * from msg_user where msg_no = ? and is_read = 0", params.get("no"));
        if (mu != null) {
            mu.setIsRead(1);
            mu.setReadTime(new Date());
            mu.update();
        }
        return Ret.ok("msg", JsonKit.toJson(msg));
    }

    //@SaCheckRole("coder")
    @RequestMapping("getReplyList")
    @WebLog(description = "请求消息回复列表")
    public Ret getReplyList(@RequestBody Map params) {
        List<MsgReply> list = MsgReply.dao.find("select * from msg_reply where msg_no = ?", params.get("no"));
        return Ret.ok("list", JsonKit.toJson(list));
    }

    @RequestMapping("reply")
    @WebLog(description = "回复消息")
    public Ret reply(MsgReply msgReply) {
        msgReply.setNo(UUID.randomUUID().toString())
                .setCreateUserId(getSessionUserId())
                .setCreateUserName(getSessionUsername())
                .setRegion(getSessionUserRegion())
                .save();
        return Ret.ok("msg", "回复成功").set("reply", JsonKit.toJson(msgReply));
    }

    public Ret getData(@RequestBody Map params) {
        User user = (User) StpUtil.getSession().get("user");
        String sqlString = "SELECT t1.id,t2.no,t2.title,t2.content,t2.create_time,t2.create_user_name,t2.hits,t2.pub_time,t1.is_read"
                + " FROM msg_user t1 LEFT JOIN msg t2 ON t1.msg_no = t2.no"
                + " where t1.userid = '" + user.getUserid() + "'"
                + " and t1.region = '" + user.getRegion() + "'";
        if (params.get("title") != null) {
            sqlString += " and title like '" + params.get("title") + "'";
        }
        if (params.get("content") != null) {
            sqlString += " and content like '" + params.get("content") + "'";
        }
        sqlString += " order by t1.is_read";
        SqlPara sql = new SqlPara();
        sql.setSql(sqlString);
        Page<Record> page = Db.use(base).paginate(Integer.valueOf(params.get("currentPage").toString()), Integer.valueOf(params.get("pageSize").toString()), sql);
        return Ret.ok("msg", "成功").set("list", page.getList()).set("totalResult", page.getTotalRow());
    }

    /**
     * @note 确认发布消息
     * @time 2024年03月26日 09:58:00
     * @author Ray
     */
    @RequestMapping("pub")
    @WebLog(description = "确认发布消息")
    @Transactional("baseTransactionManager")
    public Ret pub(@RequestBody Msg msg) {
        msg.setNo(UUID.randomUUID().toString());
        if (!msg.getIsAll()) {
            msg.setUserNum(String.valueOf(msg.getUserids().split(",").length));
        } else {
            msg.setUserNum("全员");
        }
        if (msg.getStatu() == 1) {
            msg.setPubTime(new Date());
        }
        msg.setCreateUserId(getSessionUserId());
        msg.setCreateUserName(getSessionUsername());
        msg.setRegion(getSessionUserRegion());
        if (msg.getId() != null) {
            msg.update();
        } else {
            msg.save();
        }
        if (msg.getStatu() == 1) {
            if (msg.getUserids() != null && !"".equals(msg.getUserids())) {
                String[] user = msg.getUserids().split(",");
                for (int i = 0; i < user.length; i++) {
                    MsgUser mu = new MsgUser();
                    mu.setRegion(getSessionUserRegion());
                    mu.setMsgNo(msg.getNo());
                    mu.setUserid(user[i]);
                    mu.save();
                }
            } else {
                List<User> user = User.dao.find("select * from user where region = ?", getSessionUserRegion());
                for (int i = 0; i < user.size(); i++) {
                    MsgUser mu = new MsgUser();
                    mu.setRegion(getSessionUserRegion());
                    mu.setMsgNo(msg.getNo());
                    mu.setUserid(user.get(i).getUserid());
                    mu.save();
                }
            }
            JSONObject message = new JSONObject();
            message.put("title", "您收到一则发文");
            message.put("content", msg.getTitle());
            SysmsgWebsocket.sendMessage(getSessionUserRegion(), message.toJSONString(), msg.getUserids());
        }
        return Ret.ok("msg", msg.getStatu() == 1 ? "发布成功" : "保存待发成功");
    }
}
